package com.easypay.demo.controller;

import com.alibaba.fastjson.JSON;
import com.easypay.demo.service.PayService;
import com.easypay.demo.vo.DrawVO;
import com.easypay.demo.vo.InputVO;
import com.easypay.demo.vo.PayNotifyVO;
import com.easypay.demo.vo.RequestOrderVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class DemoController {
    private final static Logger LOGGER = LoggerFactory.getLogger(DemoController.class);

    @Autowired
    PayService payService;

    @Autowired
    RestTemplate restTemplate;

    @RequestMapping("pay")
    public Object pay(@RequestBody InputVO vo){
        LOGGER.info("input:{}", JSON.toJSONString(vo));
        RequestOrderVO requestVO = new RequestOrderVO();
        requestVO.setAmount(vo.getMoney());
        requestVO.setDescription(vo.getTips());
        // 设置订单号
        requestVO.setOutTradeNo(RandomStringUtils.randomAlphanumeric(16));
        Object o = payService.pay(requestVO);
        LOGGER.info("output:{}", JSON.toJSONString(o));
        return o;
    }

    @RequestMapping(value = "notify", method = RequestMethod.POST)
    public String receiveNotify(HttpServletRequest request, @RequestBody PayNotifyVO payNotifyVO){
        String sign = request.getHeader("X-Auth-Sign");
        LOGGER.info("sign:{}", sign );
        if (payService.verify(payNotifyVO, sign)){
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Content-Type", "application/json");
            ResponseEntity<String> resp = restTemplate.exchange("http://127.0.0.1:6002/YST/payCallback", HttpMethod.POST
                    , new HttpEntity<>(payNotifyVO, requestHeaders)
                    , String.class);

            return resp.getBody();
        } else {
            LOGGER.error("notify sign error");
            return "{\"error\"}";
        }
    }

    @RequestMapping("testDraw")
    public String testDraw(@RequestBody DrawVO vo){
        return payService.createDraw(vo);
    }

    @GetMapping("testDrawDetail")
    public String testDrawDetail(){
        payService.getDrawInfo();
        return "ok";
    }

    @GetMapping("testOrderDetail")
    public String testOrderDetail(){
        payService.getPayOrderInfo();
        return "ok";
    }
}
